<?php

namespace app\api\controller\v47;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\chat\HzChatLastSendTimeRecord;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\lib\Util;
use app\common\model\Recode;

class AiChat extends Auth2
{
    public function getCharDetails()
    {
        $rid = input('rid/d', 0);
        $rid2 = input('rid2/d', 0);
        $minId = input('min_id/d', 0);
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $chatConfig = (new AppConfig())->configInfo('chat_config');
        if (Util::CheckAppVersion('2.10.5') !== '小')
        {
            $vipFreeNum = $chatConfig['vip_free_num_today'] ?? 5;
        } else
        {
            $vipFreeNum = 3;
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小' && $minId !== 0)
        {   // 安卓  并且 版本 低于2.10.6
            $minId += 1000000;
        }
        if (!$this->user)
        {
            $initData = $hzChatRecordDetailsModel->getNotLogList();
            if (!isset($chatConfig['recommend_question_hide']) || !$chatConfig['recommend_question_hide'])
            {
                $initData = $hzChatRecordDetailsModel->addRecommendQuestionResert($initData, 0);
            }
            $resData = [
                'total' => count($initData),
                'surplus_num' => 0,
                'official_avatar' => $hzChatRecordDetailsModel->officialAvatar,
                'avatar' => '',
                'num' => (int)($chatConfig['free_num'] ?? 2),
                'input_text' => '登录后向准准提问哦～',
                'vip_recommend' => [
                    'tip' => '小行星会员每日可免费提问' . $vipFreeNum . '次',
                    'btn_name' => '现在开通',
                ],
                'data' => $hzChatRecordDetailsModel->dataListResert($initData, false),
            ];

            return show(config('code.success'), '请求成功', $resData);
        }
        $recodeInfo = null;
        $rid = $rid ?: (int)($this->user['rid'] ?? 0);
        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
            {
                return show(config('code.error'), '服务异常，档案不存在');
            }

            if ($rid2 > 0 && $rid === $rid2)
            {
                $rid2 = -1;
            }
        } else
        {
            $rid2 = 0;
        }

        if ($rid2 > 0)
        {
            $recodeInfo2 = (new Recode())->getRecode(['id' => $rid2]);
            if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'] || $recodeInfo2['status'] != 1)
            {
                return show(config('code.error'), '服务异常，档案不存在');
            }
        }

        $hzChatRecordModel = new HzChatRecord();
        // 通过rid 取当前会话ID
        if ($rid)
        {   // 有自己的档案
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {   // 没有自己的档案 437
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }

        if ($chatId)
        {   // 有会话记录  取当前的会话记录
            $resData = $hzChatRecordDetailsModel->getPageDatas($chatId, 10, $minId);
            $chatData = $hzChatRecordModel->getInfoById($chatId);
            if ($rid2 === -1)
            {
                $rid2 = 0;
                if (!isset($chatData['rid2']) || $chatData['rid2'] !== 0)
                {
                    $hzChatRecordModel->updateData($chatId, $this->user['id'], ['rid2' => 0]);
                }
            } else
            {
                if ($rid2 > 0 && (!isset($chatData['rid2']) || $rid2 !== $chatData['rid2']))
                {
                    $hzChatRecordModel->updateData($chatId, $this->user['id'], ['rid2' => $rid2]);
                } else
                {
                    $rid2 = $chatData['rid2'] ?? 0;
                    $recodeInfo2 = (new Recode())->getRecode(['id' => $rid2]);
                    if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'] || $recodeInfo2['status'] != 1)
                    {   // 副档案 已删除 或不存在
                        $hzChatRecordModel->updateData($chatId, $this->user['id'], ['rid2' => 0]);
                        $rid2 = 0;
                    }
                }
            }
        } else
        {   // 没有会话记录 创建新的会话
            $nowTimw = $this->request->time();
            $rid2 = max($rid2, 0);
            $insertData = [
                'uid' => $this->user['id'],
                'rid' => $rid,
                'rid2' => $rid2,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
                'update_time' => $nowTimw,
            ];
            if (Util::commentCheck($this->user['id'], ['action' => 'AiChat.getCharDetails', 'uid' => $this->user['id'], 'rid' => $rid], 2))
            {   // 操作频繁 请稍后再试～
                return show(config('code.error'), '');
            }
            // 创建新的会话
            $chatId = $hzChatRecordModel->initSave($insertData);
            // 记录 自己的档案 用户会话 ID 信息
            if ($rid === 0 || $rid === $this->user['rid'])
            {   // 没有自己的档案 或者 自己的档案
                (new HzChatLastSendTimeRecord())->UpdateData($this->user['id'], ['chat_id' => $chatId]);
            }
            // 发送系统会话
            $insertInitData = $hzChatRecordDetailsModel->getInitData($this->user['id'], $chatId, $recodeInfo);
            $data = $hzChatRecordDetailsModel->insertInitData($chatId, $insertInitData);
            $resData = [
                'total' => count($data),
                'surplus_num' => 0,
                'data' => $data,
            ];
        }

        if ($resData['data'])
        {
            $isShowZan = $minId === 0;  // 最近10条数据 踩显示 点赞相关信息
            // 添加推荐问题
            if ($resData['surplus_num'] < 2)
            {   // 剩余数据数量 小于2
                $resData['data'] = $hzChatRecordDetailsModel->addRecommendQuestionResert($resData['data'], $this->user['rid']);
            }

            $resData['data'] = $hzChatRecordDetailsModel->dataListResert($resData['data'], $isShowZan);
        }

        $resData['official_avatar'] = $hzChatRecordDetailsModel->officialAvatar;
        if ($recodeInfo)
        {
            $resData['avatar'] = $recodeInfo['avatar'];
        } else
        {
            $resData['avatar'] = '';
        }
        // 剩余 会话 次数
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);    //  剩余对话次数
        $resData['num'] = $numData['res_num'];
        $resData['input_text'] = $hzChatRecordDetailsModel->getInputPlaceholder($numData);
        $resData['vip_recommend'] = $numData['vip_level'] > 0 ? null : [
            'tip' => '小行星会员每日可免费提问' . $vipFreeNum . '次',
            'btn_name' => '现在开通',
        ];

        $resData['rid'] = $rid;
        $resData['rid2'] = $rid2;
        $resData['call_avatar'] = '/test/consult_chat/call_avatar.png';
        $resData['call_nickname'] = '星座女神 莫小奇';
        $resData['call_min_num'] = 3;

        return show(config('code.success'), '请求成功', $resData);
    }
}
